import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:p_location/common/constant/sp_key.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/no_result_widget.dart';
import 'package:p_location/common/widget/right_arrow_item.dart';
import 'package:p_location/common/widget/split_title_view.dart';
import 'package:p_location/home/ui/person/page_employee_detail.dart';
import 'package:p_location/home/ui/person/page_guest_detail.dart';
import 'package:p_location/home/ui/person/page_worker_detail.dart';
import 'package:p_location/home/ui/vehicle/page_inner_car_detail.dart';
import 'package:p_location/home/ui/vehicle/page_outer_car_detail.dart';
import 'package:p_location/map/constant/map_http_url.dart';
import 'package:p_location/map/obj/gits_sn_info.dart';
import 'package:p_location/map/obj/risk_zone_bundle_item.dart';
import 'package:p_location/map/obj/risk_zone_data.dart';
import 'package:p_location/map/obj/risk_zone_point.dart';
import 'package:p_location/map/obj/risk_zone_rail.dart';
import 'package:p_location/map/res/dept_tree_info.dart';
import 'package:p_location/map/res/gis_person_type_info.dart';
import 'package:p_location/map/res/gis_person_type_res.dart';
import 'package:p_location/map/res/icon_dictionary_res.dart';
import 'package:p_location/map/res/map_elements_info.dart';
import 'package:p_location/map/res/map_elements_res.dart';
import 'package:p_location/map/res/res_map_alarm_info.dart';
import 'package:p_location/map/res/res_risk_zone.dart';
import 'package:p_location/map/res/search_person_detail.dart';
import 'package:p_location/map/res/search_person_info.dart';
import 'package:p_location/map/res/search_person_res.dart';
import 'package:p_location/map/ui/dept_info_tree_page.dart';
import 'package:p_location/map/ui/page_person_trace.dart';
import 'package:p_location/map/ui/page_search_person.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:p_location/user/obj/obj_map_path.dart';
import 'package:p_location/utils/navigator_util.dart';
import 'package:p_location/utils/parse_params_util.dart';
import 'package:p_location/utils/shared_preferences_util.dart';
import 'package:p_location/utils/string_util.dart';
import 'package:p_location/utils/toast_util.dart';
import 'package:p_location/websocket/hi_socket.dart';
import 'package:p_location/websocket/location_req.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:dio/dio.dart';

import 'menus/map_menus.dart';
import 'obj/gis_socket_detail.dart';
import 'obj/gis_socket_info.dart';
import 'obj/gis_socket_res.dart';
import 'dart:convert' as convert;

import 'obj/icon_info.dart';
import 'package:loading/loading.dart';
import 'package:loading/indicator/ball_spin_fade_loader_indicator.dart';

import 'obj/risk_zone_info.dart';

class GisMapPage extends StatefulWidget {
  final SearchPersonDetail realTrackTarget;
  final String title;

  GisMapPage({Key key, this.realTrackTarget, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _GisMapPageState();
  }
}

class _GisMapPageState extends State<GisMapPage>
    with WidgetsBindingObserver,AutomaticKeepAliveClientMixin {
  bool lock = false;

  String eMsg = "";

  bool isConfigurationLacked = false;

  //是否单个的 实时跟踪 比如从人员车辆那里过来的
  bool isSingleRealTrack = false;

  bool isBuildIdObtained = false;

  bool isLoading = true;

  dynamic firstFloorId; //计算得出的楼层id eg.FloorId5->5

  String account = "";
  String buildId = "";

  bool firstSummarySuccessFlag = false;

  List<SearchPersonDetail> _detailList;

  //人员类型列表
  List<GisPersonTypeInfo> personTypeList = [];

  String errorMsg = "";

  Timer _startTimer;

  Timer _summaryTimer;

  Timer _locationTimer;

  Timer _alarmInfoTimer;

  //信息字典
  Map<String, dynamic> infoDictionary;

  List<IconInfo> iconDictionary;

  List<String> alarmSns = [];

  List<bool> mapShowStatusList = [true, true, true];

  String mapType = "2D平面图";

  //选择的人员类型
  List<int> chosenJobIds = [];

  DeptTreeInfo chosenDeptTreeInfo;

  List<bool> confirmedMapShowStatusList = [true, true, true];

  String confirmedMapType = "2D平面图";

  //选择的人员类型
  List<int> confirmedChosenJobIds = [];

  DeptTreeInfo confirmedChosenDeptTreeInfo;

  List<GisSocketDetail> survivedDetails;

  SearchPersonDetail realTimeTrackTarget;

  bool personTypeExpandFlag = false;

  WebViewController controller;

  HiSocket _hiSocket;

  int summaryInterval = 20;

  int locationInterval = 5;

  bool lastOpenStatus = false;

  bool isRequestingPoi = false;

  final String hintText = "请输入姓名/定位卡号/车牌号";

  final Radius cornerRadius = Radius.circular(10);

  SearchPersonDetail chosenSn;

  CancelToken cancelToke;

  bool isTopArrow = false;

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  List<RiskZoneBundleItem> bundleItems = [];

  String bundlePoints = "";

  bool isResumed = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    if (widget.realTrackTarget != null) {
      realTimeTrackTarget = widget.realTrackTarget;
      chosenSn = realTimeTrackTarget;
      isSingleRealTrack = true;
//      print(realTimeTrackTarget.sn);
      WidgetsBinding.instance.addPostFrameCallback((callback) {
        print("addPostFrameCallback be invoke");
        showBottomSheet2(true, true, realTimeTrackTarget);
      });
    }
    readBuildInfo();
  }

  handleMessage(message) {
    if (infoDictionary == null || infoDictionary.length == 0) {
      return;
    }
    if (iconDictionary == null || iconDictionary.length == 0) {
      return;
    }
    Map<String, dynamic> concreteInfo = convert.jsonDecode(message);
//    print("===");
//    print(concreteInfo["requestMethod"].toString());
//    print("===");
//    print(concreteInfo["requestMethod"].toString() == "location");
    if (concreteInfo["requestMethod"].toString() != "summary" &&
        concreteInfo["requestMethod"].toString() != "location") {
//      print("return了");
      return;
    } else {
      if (concreteInfo["requestMethod"].toString() == "summary") {
        _startTimer?.cancel();
        if (!firstSummarySuccessFlag) {
          firstSummarySuccessFlag = true;
          formSend();
        }
        if (isSingleRealTrack) {
          _setRealTrackTarget();
        }
      }
    }
    GisSocketRes res = GisSocketRes.fromJson(concreteInfo);
    if (res != null && res.data != null) {
      GisSocketInfo info = res.data;
      if (info != null && info.code == 0) {
        List<GisSocketDetail> details = info.data;
        survivedDetails = [];
        if (details != null && details.length > 0) {
          for (var i = 0; i < details.length; i++) {
//            print("找到了对应sn卡号的了");
//            print(infoDictionary[details[i].sn]);
            if (infoDictionary[details[i].sn] == null) {
              continue;
            }
//            if(details[i].sn != "202107181001"){
//              continue;
//            }
            GisSnInfo gisSnInfo =
                GisSnInfo.fromJson(infoDictionary[details[i].sn]);
            if (gisSnInfo != null) {
              bool isShow = true;
              if (realTimeTrackTarget != null &&
                  realTimeTrackTarget.sn != gisSnInfo.sn) {
                if (isSingleRealTrack) {
                  continue;
                }
//                continue;
                isShow = false;
              }
              if (confirmedChosenDeptTreeInfo != null) {
                if (gisSnInfo.departId != confirmedChosenDeptTreeInfo.id) {
//                  continue;
                  isShow = false;
                }
              }
//              print(chosenJobIds);
              if (confirmedChosenJobIds != null &&
                  confirmedChosenJobIds.length > 0 &&
                  !confirmedChosenJobIds.contains(gisSnInfo.jobId)) {
//                continue;
                isShow = false;
              }
              IconInfo iconInfo = iconDictionary
                  .firstWhere((element) => element.id == gisSnInfo.iconId);
//              print(convert.jsonEncode(gisSnInfo));
              if (iconInfo != null) {
                details[i].icon = iconInfo.iconName;
                details[i].iconAlarm = iconInfo.warningName;
              }
              details[i].type = gisSnInfo.bindType;
              details[i].jobId = gisSnInfo.jobId;
              details[i].deptId = gisSnInfo.departId;
              details[i].name = gisSnInfo.binderName;
              if (alarmSns != null) {
                details[i].isAlarm = alarmSns.contains(gisSnInfo.sn);
              }
//              print('isSHow$isShow');
              details[i].isShow = false;
              if (realTimeTrackTarget != null &&
                  realTimeTrackTarget.sn == gisSnInfo.sn) {
                details[i].isRealTrack = true;
              }

              survivedDetails.add(details[i]);
//              print("1234:" + convert.jsonEncode(details[i]));
            }
          }
//          print("append后的" + convert.jsonEncode(survivedDetails));
          controller
              ?.evaluateJavascript(
                  'xxx("${res.requestMethod}",${convert.jsonEncode(survivedDetails)})')
              ?.then((result) {
//            print('controller是否为null${controller == null}');
            // You can handle JS result here.
          });
//          if (firstFloorId == null &&
//              survivedDetails != null &&
//              survivedDetails.length > 0) {
//            String floorNo = survivedDetails[0].floorNo;
//            if (StringUtil.isNotEmpty(floorNo)) {
//              setState(() {
//                firstFloorId = floorNo.substring(5);
//              });
//
//              _setFloorId(firstFloorId);
//            }
//          }
        }
      }
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
//    controller.clearCache();
    _startTimer?.cancel();
    _summaryTimer?.cancel();
    _locationTimer?.cancel();
    _alarmInfoTimer?.cancel();
    _hiSocket?.close();
    if (cancelToke != null) {
      cancelToke.cancel();
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print('应用程序可见并响应用户输入。');
        isResumed = true;
        break;
      case AppLifecycleState.inactive:
        print('应用程序处于非活动状态，并且未接收用户输入');
        break;
      case AppLifecycleState.paused:
        print('用户当前看不到应用程序，没有响应');
        isResumed = false;
        break;
//      case AppLifecycleState.suspending:
//        print('应用程序将暂停。');
//        break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    return _getScaffold();
  }

  _getScaffold() {
    return RotatedBox(
      quarterTurns: 0,
      child: Scaffold(
        key: _scaffoldKey,
        appBar: isSingleRealTrack
            ? AppBar(
                title: Text("追踪"),
                centerTitle: true,
                elevation: 0,
                brightness: Brightness.dark,
                leading: IconButton(
                    tooltip: '返回',
                    icon: Icon(Icons.arrow_back_ios, color: Colors.white),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              )
            : null,
        endDrawer: isSingleRealTrack ? null : _drawer,
        onEndDrawerChanged: (isOpened) {
//          print('isOpend$isOpened');
          if (isOpened) {
//            print('lastOpenStatus$lastOpenStatus');
            if (lastOpenStatus) {
              lastOpenStatus = isOpened;
              return;
            }
            setState(() {
//              print("设置");
//              print(confirmedMapShowStatusList);
              mapShowStatusList[0] = confirmedMapShowStatusList[0];
              mapShowStatusList[1] = confirmedMapShowStatusList[1];
              mapShowStatusList[2] = confirmedMapShowStatusList[2];
//              mapShowStatusList[3] = confirmedMapShowStatusList[3];

              mapType = (confirmedMapType == "2D平面图") ? "2D平面图" : "卫星图";

              chosenJobIds = [];
              if (confirmedChosenJobIds != null &&
                  confirmedChosenJobIds.length > 0) {
                confirmedChosenJobIds.forEach((element) {
                  chosenJobIds.add(element);
                });
              }

              chosenDeptTreeInfo = null;
              if (confirmedChosenDeptTreeInfo != null) {
                chosenDeptTreeInfo = DeptTreeInfo(
                    id: confirmedChosenDeptTreeInfo.id,
                    label: confirmedChosenDeptTreeInfo.label);
              }
//              mapShowStatusList = confirmedMapShowStatusList;
//              print(mapShowStatusList);
//              chosenJobIds = confirmedChosenJobIds;
//              mapType = confirmedMapType;
//              chosenDeptTreeInfo = confirmedChosenDeptTreeInfo;
            });
          }
          lastOpenStatus = isOpened;
        },
        body: _getContentView(),
      ),
    );
  }

  _getContentView() {
    return isBuildIdObtained
        ? (StringUtil.isNotEmpty(eMsg)
            ? NoResultWidget('images/img_no_accident.png', eMsg)
            : Stack(
                children: <Widget>[
                  new GestureDetector(
                    onTapDown:(event){},
                    child: WebView(
//            initialUrl: 'http://127.0.0.1:9000/html/index31.html',
                        initialUrl: ObjMapPath.getInitUrl(false),
                        // 加载的url
                        javascriptMode: JavascriptMode.unrestricted,
                        navigationDelegate: (NavigationRequest request) {
                          if (request.url.startsWith('js://webview')) {
                            if (realTimeTrackTarget != null) {
                              print("实时跟踪状态,不响应点击");
                            } else {
                              print("接收到了点击事件");
                              print(request.url);
//              var x = ParseParamsUtil.parse(request.url);
//              print(x);
//              showBottomSheet();
                              _getNearbyPoi(ParseParamsUtil.parse(request.url));
                            }
                          } else if (request.url
                              .startsWith("js://onMapLoadCompleted")) {
                            print("地图加载完毕...");
                            setState(() {
                              isLoading = false;
                              _setChosenMapType();
                            });
                          } else if (request.url
                              .startsWith("js://onReadConfigurationFailed")) {
                            setState(() {
                              isLoading = false;
                              isConfigurationLacked = true;
                              eMsg = "jpg地图缺失，请联系实施工程师";
                            });
                          }
                          return NavigationDecision.prevent;
                        },
                        onWebViewCreated: (WebViewController web) {
                          controller = web;
                        },
                        onPageFinished: (String value) {
                          setState(() {
                            isLoading = false;
                            print('onPageFinished$value');
                          });
                        },

                        onWebResourceError:(error){
                          // eMsg = "网页加载失败...";
                          print("======");
                          print('errorCode:${error.errorCode}');
                          print('errorType:${error.errorType}');
                          print('errorType:${error.failingUrl}');
                          print("======");
                        }
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 30),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          child: Flex(direction: Axis.horizontal, children: [
                            Expanded(
                                child: GestureDetector(
                                    onTap: () {
                                      Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                  builder: (context) =>
                                                      PageSearchPerson(true)))
                                          .then((value) {
                                        print("选取了人员" + value?.name);
                                        setState(() {
                                          chosenSn = value;
                                          getFullInfo();
//                                _getNearbyPoi(params)
                                        });
                                      });
                                    },
                                    child: _searchBar))
                          ]),
                        )
                      ],
                    ),
                  ),
                  Positioned(
                    right: 15,
                    top: 100,
                    child: Builder(
                      builder: (context) {
                        return Offstage(
                          offstage: _isTrackingMode(),
                          child: GestureDetector(
                            onTap: () {
                              Scaffold.of(context).openEndDrawer();
//                  _setFloorId(2);
                            },
                            child: Container(
                              width: 32,
//                  height: 52,
                              padding: EdgeInsets.only(
                                  top: 8, bottom: 8, left: 2, right: 2),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(3))),
                              child: Column(
                                children: [
                                  Image.asset(
                                    'images/icon_gis_menu.png',
                                    width: 25,
                                    height: 25,
                                  ),
                                  Text("图层",
                                      style: TextStyle(
                                          color: Color.fromARGB(200, 0, 0, 0),
                                          fontSize: 12))
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
//              Positioned(
//                bottom: 5,
//                child: Offstage(
//                  offstage: realTimeTrackTarget == null,
//                  child: Container(
////              margin: EdgeInsets.only(left: 200,right: 200),
//
//                    width: MediaQuery.of(context).size.width,
//                    alignment: Alignment.center,
//                    child: Container(
//                      color: Colors.white,
//                      width: 100,
//                      child: Column(
//                        children: [
//                          IconButton(
//                              onPressed: () {
//                                realTimeTrackTarget = null;
//                                _setRealTrackTarget();
//                              },
//                              icon: Icon(Icons.cancel)),
//                          Text(realTimeTrackTarget?.name ?? "")
//                        ],
//                      ),
//                    ),
//                  ),
//                ),
//              ),
                  Positioned(
                    left: 32,
                    bottom: 130,
                    child: Offstage(
                      offstage: realTimeTrackTarget == null,
                      child: GestureDetector(
                        onTap: () {
                          if (realTimeTrackTarget != null) {
                            showBottomSheet2(true, true, realTimeTrackTarget);
                          }
                        },
                        child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.all(5),
                            child: Column(
                              children: [
                                Container(
                                  alignment: Alignment.center,
                                  child: Icon(
                                    Icons.remove_red_eye,
                                    size: 18,
                                  ),
                                )
                              ],
                            )),
                      ),
                    ),
                  ),
                  Positioned(
                    left: 32,
                    bottom: 170,
                    child: Offstage(
                      offstage:
                          isSingleRealTrack || realTimeTrackTarget == null,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            realTimeTrackTarget = null;
                            _setRealTrackTarget();
                          });
                        },
                        child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.all(5),
                            child: Column(
                              children: [
                                Container(
                                  alignment: Alignment.center,
                                  child: Icon(
                                    Icons.cancel,
                                    size: 18,
                                  ),
                                )
                              ],
                            )),
                      ),
                    ),
                  ),
                  Offstage(offstage: !isLoading, child: _getLoadingView())
                ],
              ))
        : _getLoadingView();
  }

  _getLoadingView() {
    return Center(
      child: Loading(
          indicator: BallSpinFadeLoaderIndicator(),
          size: 100.0,
          color: Colors.blue),
    );
  }

  get _drawer => Drawer(
        ///edit start
        child: Stack(
          children: [
            Container(
              margin: EdgeInsets.only(top: 13, bottom: 50),
              child: ListView(
                children: <Widget>[
                  SplitTitleView(
                    "地图显示",
                    textColor: Color.fromRGBO(0, 0, 0, 0.65),
                    backgroundColor: Color.fromRGBO(239, 239, 243, 1),
                  ),
                  Container(
                    color: Colors.white,
                    child: GridView.builder(
                        itemCount: MapMenus.menus.length,
                        padding: EdgeInsets.all(10),
                        shrinkWrap: true,
                        physics: new NeverScrollableScrollPhysics(),
                        //禁用滑动事件
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4, mainAxisSpacing: 20),
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            onTap: () {
                              setState(() {
                                mapShowStatusList[index] =
                                    !mapShowStatusList[index];
                              });
//                          Navigator.of(context).pop();
                            },
                            onTapDown: (event) {},
                            child: Column(
                              children: [
                                Stack(
                                  children: [
                                    Container(
                                      decoration: BoxDecoration(
                                          color: mapShowStatusList[index]
                                              ? Colors.blue
                                              : Colors.white,
                                          borderRadius:
                                              BorderRadius.circular(100)),
                                      padding: EdgeInsets.all(2),
                                      child: Image.asset(
                                        MapMenus.menus[index].icon,
                                        width: 45,
                                        height: 45,
                                      ),
                                    ),
                                    Positioned(
                                      child: Offstage(
                                        offstage: !mapShowStatusList[index],
                                        child: Container(
                                          decoration: BoxDecoration(
                                              color: Colors.blue,
                                              borderRadius:
                                                  BorderRadius.circular(100)),
                                          child: Icon(
                                            Icons.done,
                                            size: 15,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                      right: 1,
                                      bottom: 1,
                                    )
                                  ],
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 3),
                                  child: Text(
                                    MapMenus.menus[index].title,
                                    style: TextStyle(
                                        color: Color(0xff000000), fontSize: 12),
                                  ),
                                )
                              ],
                            ),
                          );
                        }),
                  ),
                  SplitTitleView(
                    "地图类型",
                    textColor: Color.fromRGBO(0, 0, 0, 0.65),
                    backgroundColor: Color.fromRGBO(239, 239, 243, 1),
                  ),
                  Container(
                    color: Colors.white,
                    child: GridView.builder(
                        itemCount: MapMenus.mapTypes.length,
                        padding: EdgeInsets.all(10),
                        shrinkWrap: true,
                        physics: new NeverScrollableScrollPhysics(),
                        //禁用滑动事件
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4, mainAxisSpacing: 20),
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            onTap: () {
                              setState(() {
                                mapType = MapMenus.mapTypes[index].title;
                              });
//                          Navigator.of(context).pop();
                            },
                            onTapDown: (event) {},
                            child: Column(
                              children: [
                                Stack(
                                  children: [
                                    Container(
                                      decoration: BoxDecoration(
                                          color: mapType ==
                                                  MapMenus.mapTypes[index].title
                                              ? Colors.blue
                                              : Colors.white,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      padding: EdgeInsets.all(2),
                                      child: Image.asset(
                                        MapMenus.mapTypes[index].icon,
                                        width: 45,
                                        height: 45,
                                      ),
                                    ),
                                    Positioned(
                                      child: Offstage(
                                        offstage: mapType !=
                                            MapMenus.mapTypes[index].title,
                                        child: Container(
                                          decoration: BoxDecoration(
                                              color: Colors.blue,
                                              borderRadius:
                                                  BorderRadius.circular(100)),
                                          child: Icon(
                                            Icons.done,
                                            size: 15,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                      right: 1,
                                      bottom: 1,
                                    )
                                  ],
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: 3),
                                  child: Text(
                                    MapMenus.mapTypes[index].title,
                                    style: TextStyle(
                                        color: Color(0xff000000), fontSize: 12),
                                  ),
                                )
                              ],
                            ),
                          );
                        }),
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        personTypeExpandFlag = !personTypeExpandFlag;
                        isTopArrow = !isTopArrow;
                      });
                    },
                    child: SplitTitleView(
                      "人员筛选",
                      textColor: Color.fromRGBO(0, 0, 0, 0.65),
                      backgroundColor: Color.fromRGBO(239, 239, 243, 1),
                      hasRightArrow: true,
                      isTopArrow: isTopArrow,
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    child: GridView.builder(
                        itemCount: personTypeExpandFlag
                            ? personTypeList?.length ?? 0
                            : ((personTypeList?.length ?? 0) > 5
                                ? 6
                                : personTypeList.length),
                        padding: EdgeInsets.all(10),
                        shrinkWrap: true,
                        physics: new NeverScrollableScrollPhysics(),
                        //禁用滑动事件
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3,
                            mainAxisSpacing: 5,
                            crossAxisSpacing: 6,
                            childAspectRatio: 2.5),
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            onTap: () {
//                              print("onTap");
                              setState(() {
                                if (chosenJobIds
                                    .contains(personTypeList[index].value)) {
                                  chosenJobIds
                                      .remove(personTypeList[index].value);
                                } else {
                                  chosenJobIds.add(personTypeList[index].value);
                                }
                                personTypeList[index].chosenFlag =
                                    !personTypeList[index].chosenFlag;
//                                print("选择的jogId");
//                                print(chosenJobIds);
                              });
                            },
                            onTapDown: (event) {},
                            child: Container(
                              decoration: BoxDecoration(
                                  color: chosenJobIds
                                          .contains(personTypeList[index].value)
                                      ? Color.fromRGBO(56, 160, 253, 0.9)
                                      : Color.fromRGBO(239, 239, 243, 1),
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(18))),
                              alignment: Alignment.center,
                              padding: EdgeInsets.only(left: 12, right: 12),
                              child: Text(
                                personTypeList[index].label,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: chosenJobIds.contains(
                                            personTypeList[index].value)
                                        ? Colors.white
                                        : Color.fromRGBO(0, 0, 0, 1),
                                    fontSize: 15),
                              ),
                            ),
                          );
                        }),
                  ),
                  SplitTitleView(
                    "部门",
                    textColor: Color.fromRGBO(0, 0, 0, 0.65),
                    backgroundColor: Color.fromRGBO(239, 239, 243, 1),
                    hasRightArrow: false,
                  ),
                  RightArrowItem(
                    chosenDeptTreeInfo != null
                        ? chosenDeptTreeInfo.label
                        : "请选择",
                    "",
                    () {
                      Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => DeptInfoTreePage()))
                          .then((value) {
//                        print("选取了人员" + value.name);
                        setState(() {
                          chosenDeptTreeInfo = value;
                        });
                      });
                    },
                    isMust: false,
                  )
                ],
              ),
            ),
            Positioned(
                bottom: 1,
                child: GestureDetector(
                  onTap: () {
//                NavigatorUtil.push(context, PageTraceRecord());
//                logout();
                  },
                  child: Container(
                    color: Colors.white,
                    width: 304,
                    height: 50,
                    child: Flex(
                      direction: Axis.horizontal,
                      children: [
                        Expanded(
                            child: GestureDetector(
                          onTap: () {
//                            print("重置");
                            reset();
                          },
                          child: Container(
                            color: Colors.white,
                            alignment: Alignment.center,
                            child: Text(
                              "重置",
                              style: TextStyle(
                                  color: Color.fromRGBO(26, 103, 250, 1)),
                            ),
                          ),
                        )),
                        FractionallySizedBox(
                          heightFactor: 1,
                          child: Container(
                            color: Color.fromARGB(33, 0, 0, 0),
                            width: 0.5,
                            child: Text(""),
                          ),
                        ),
                        Expanded(
                            child: GestureDetector(
                          onTap: () {
//                            print("确定");
                            confirmFilter();
                          },
                          child: Container(
                              alignment: Alignment.center,
                              child: Text(
                                "确定",
                                style: TextStyle(
                                    color: Color.fromRGBO(26, 103, 250, 1)),
                              )),
                        ))
                      ],
                    ),
                  ),
                ))
          ],
        ),

        ///edit end
      );

  showBottomSheet() {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (c) {
          return Offstage(offstage: false, child: _draggable);
        });
  }

  showBottomSheet2(bool isDirect, bool isViewMode, SearchPersonDetail detail) {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (c) {
          return Offstage(
              offstage: false,
              child: Container(
                height: 300,
                padding: EdgeInsets.only(left: 10, right: 10),
                alignment: Alignment.topRight,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(5),
                        topRight: Radius.circular(5))),
                child: Wrap(
                  children: [
                    Column(
                      children: [
                        Container(
                            margin: EdgeInsets.only(top: 10),
                            height: 70,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Column(
                                  children: [
                                    Image.asset(
                                      "images/icon_inner_person.png",
                                      width: 45,
                                      height: 45,
                                    ),
                                    Container(
                                      child: Text(
                                        detail?.name ?? "-",
                                        style: TextStyle(
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 15),
                                      ),
                                    )
                                  ],
                                ),
                                Offstage(
                                  offstage: detail.typeName == '员工',
                                  child: GestureDetector(
                                    onTap: () {
                                      print(detail.typeName);
                                      jumpToDetail(detail.typeName, detail.id,
                                          detail.name);
                                    },
                                    child: Container(
                                      height: 90,
                                      child: Text(
                                        "查看详情",
                                        style: TextStyle(
                                            fontSize: 15,
                                            color: Color.fromARGB(
                                                255, 26, 103, 250)),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            )),
                        Container(
                          height: 40,
                          child: Row(
                            children: [
                              Container(
                                width: 80,
                                child: Text("员工类型:"),
                              ),
                              Text(detail?.typeName ?? '-')
                            ],
                          ),
                        ),
                        Container(
                          height: 40,
                          child: Row(
                            children: [
                              Container(
                                width: 80,
                                child: Text("定位卡号:"),
                              ),
                              Text(detail?.sn ?? '-')
                            ],
                          ),
                        ),
                        Container(
                          height: 40,
                          child: Row(
                            children: [
                              Container(
                                width: 80,
                                child: Text("部门:"),
                              ),
                              Text(detail?.departName ?? '-')
                            ],
                          ),
                        ),
                        Container(
                          height: 40,
                          child: Row(
                            children: [
                              Container(
                                width: 80,
                                child: Text("岗位:"),
                              ),
                              Text(detail?.jobName ?? '-')
                            ],
                          ),
                        ),
                        FractionallySizedBox(
                          widthFactor: 1,
                          child: Container(
                            color: Color.fromARGB(33, 0, 0, 0),
                            height: 0.5,
                            child: Text("1"),
                          ),
                        ),
                        Offstage(
                          offstage: isViewMode,
                          child: Container(
                            height: 40,
                            alignment: Alignment.center,
                            child: Flex(
                              direction: Axis.horizontal,
                              children: [
                                Expanded(
                                    child: GestureDetector(
                                  onTap: () {
                                    realTimeTrackTarget = detail;
                                    _setRealTrackTarget();
                                    if (!isDirect) {
                                      Navigator.of(context).pop();
                                    }
                                    Navigator.of(context).pop();
                                  },
                                  child: Container(
                                    alignment: Alignment.center,
                                    child: Text("实时跟踪",
                                        style: TextStyle(
                                            color: Color.fromARGB(
                                                255, 26, 103, 250))),
                                  ),
                                )),
                                Container(
                                  color: Color.fromARGB(33, 0, 0, 0),
                                  width: 0.5,
                                  height: 40,
                                  child: Text(""),
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () {
                                      NavigatorUtil.push(
                                          context,
                                          PagePersonTrace(
                                            isSingleTrace: true,
                                            chosenSn: detail,
                                          ));
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      child: Text("查询轨迹",
                                          style: TextStyle(
                                              color: Color.fromARGB(
                                                  255, 26, 103, 250))),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ));
        });
  }

  get _draggable => DraggableScrollableSheet(
      expand: false,
      initialChildSize: 0.8,
      minChildSize: 0.1,
      maxChildSize: 1,
      builder: (BuildContext context, ScrollController scrollController) {
        return Container(
          color: Colors.white,
          child: GridView.builder(
              itemCount: _detailList?.length ?? 0,
              padding: EdgeInsets.all(10),
              shrinkWrap: true,
              physics: new NeverScrollableScrollPhysics(),
              //禁用滑动事件
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4, mainAxisSpacing: 20),
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
//                      Navigator.of(context).pop();
                    print("选择了附近的人");
                    showBottomSheet2(false, false, _detailList[index]);
                  },
                  onTapDown: (event) {},
                  child: Column(
                    children: [
                      Image.asset(
                        "images/icon_inner_person.png",
                        width: 45,
                        height: 45,
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 3),
                        child: Text(
                          _detailList[index]?.name ?? "车辆的啥",
                          style:
                              TextStyle(color: Color(0xff000000), fontSize: 15),
                        ),
                      )
                    ],
                  ),
                );
              }),
        );
      });

  @override
  bool get wantKeepAlive => true;

  // 获取大屏所需要展示的所有信息

  _getAllInfo() async {
    Map<String, dynamic> params = {};
//    DioHttpClient.addHeader("buildid", "202722");
    await DioHttpClient.requestGet(
        context,
        MapHttpUrl.BIG_SCREEN_ALL_LIST_URL,
        params,
        new NetListenerImpl((Response response) {
          if (response != null && response.data != null) {
            MapElementsRes res = MapElementsRes.fromJson(response.data);
            if (res != null && res.code == 0 && res.data != null) {
              MapElementsInfo info = res.data;
              if (info != null && info.data != null) {
                infoDictionary = info.data;
                print("=====================");
                print(infoDictionary["202106180039"]);
                print("=====================");
                _runTimer();
              }
            }
          }
        }, (CommonRes errorRes) {}));
  }

  _getIconDictionary() async {
    cancelToke = CancelToken();
    Map<String, dynamic> params = {};
//    DioHttpClient.addHeader("buildid", "202722");
    await DioHttpClient.requestGet(
        context,
        MapHttpUrl.ICON_DICTIONARY_URL,
        params,
        new NetListenerImpl((Response response) {
          if (response != null && response.data != null) {
            IconDictionaryRes res = IconDictionaryRes.fromJson(response.data);
            if (res != null && res.code == 0 && res.data != null) {
              iconDictionary = res.data;
              _runTimer();
            }
          }
        }, (CommonRes errorRes) {
          eMsg = "获取icon资源失败!";
        }),
        cancelToken: cancelToke);
  }

  _getPersonTypeList() async {
    if (personTypeList != null && personTypeList.length > 0) {
      return;
    }
    Map<String, dynamic> params = {};
//    DioHttpClient.addHeader("buildid", "202722");
    await DioHttpClient.requestGet(
        context,
        MapHttpUrl.PERSON_TYPE_LIST_URL,
        params,
        new NetListenerImpl((Response response) {
          if (response != null && response.data != null) {
            GisPersonTypeRes res = GisPersonTypeRes.fromJson(response.data);
            if (res != null && res.code == 0 && res.data != null) {
              personTypeList = res.data;
            }
          }
        }, (CommonRes errorRes) {}));
  }

  _setFloorId(floorId) {
    controller?.evaluateJavascript('setFloorId($floorId)')?.then((result) {});
  }

  _setShowStatusList() {
    controller
        ?.evaluateJavascript(
            'setShowStatusList(${convert.jsonEncode(confirmedMapShowStatusList)})')
        ?.then((result) {});
  }

  _setChosenMapType() {
    int type = 1;
    if(mapType == '2D平面图'){
     type = 0;
    }
    Map<String, String> params = {};
    params[SPKey.KEY_MAP_MODE] = '$type';
    print('保存的type$type');
    SharedPreferenceHelp.save(params);
    controller
        ?.evaluateJavascript(
        'setChosenMapType($type)')
        ?.then((result) {});
  }

  _setChosenDeptId(deptId) {
    controller
        ?.evaluateJavascript('setChosenDeptId($deptId)')
        ?.then((result) {});
  }

  _setChosenJobIds() {
    controller
        ?.evaluateJavascript(
            'setChosenJobIds(${convert.jsonEncode(confirmedChosenJobIds)})')
        ?.then((result) {});
  }

  _setRealTrackTarget() {
    String target = realTimeTrackTarget == null ? "" : realTimeTrackTarget.sn;
    print('target:$target');
    controller?.evaluateJavascript('setRealTrackSn("$target")')?.then((result) {
      print("设置成功了吗");
      print(result);
    });
  }

  _doFilter() {
    controller?.evaluateJavascript('doFilter()')?.then((result) {});
  }

  _getNearbyPoi(params) async {
    isRequestingPoi = true;
    _detailList = null;
//    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        MapHttpUrl.SEARCH_NEARBY_POI_URL,
        params,
        new NetListenerImpl((Response response) {
          isRequestingPoi = false;
          if (response != null && response.data != null) {
            SearchPersonRes res = SearchPersonRes.fromJson(response.data);
            _detailList = [];
            if (res != null && res.data != null) {
              SearchPersonInfo searchPersonInfo = res.data;
              setState(() {
                if (searchPersonInfo != null) {
                  if (searchPersonInfo.employeeList != null) {
                    _detailList.addAll(searchPersonInfo.employeeList);
                  }
                  if (searchPersonInfo.guestList != null) {
                    _detailList.addAll(searchPersonInfo.guestList);
                  }
                  if (searchPersonInfo.workerList != null) {
                    _detailList.addAll(searchPersonInfo.workerList);
                  }
                  if (searchPersonInfo.innerCarList != null) {
                    _detailList.addAll(searchPersonInfo.innerCarList);
                  }
                  if (searchPersonInfo.outerCarList != null) {
                    _detailList.addAll(searchPersonInfo.outerCarList);
                  }
                }
              });

              print('取到了${_detailList.length}');
              if (_detailList.length == 0) {
                errorMsg = "查无结果";
              } else {
                errorMsg = "";
                showBottomSheet();
              }
            }
          }
        }, (CommonRes errorRes) {
          isRequestingPoi = false;
          if (errorRes != null) {
            ToastUtil.showToast(errorRes.msg);
          }
        }),
        loadingTip: "正在查询...");
  }

  reset() {
    mapShowStatusList = [true, true, true];
    mapType = "2D平面图";
    chosenJobIds = [];
    chosenDeptTreeInfo = null;
    personTypeList.forEach((element) {
      element.chosenFlag = false;
    });
    setState(() {});
  }

  filterPOIs() {}

  readBuildInfo() async {
    dynamic value = await SharedPreferenceHelp.read(SPKey.KEY_BUILD_ID);
    dynamic accountValue = await SharedPreferenceHelp.read(SPKey.KEY_ACCOUNT);
    String mapMode = await SharedPreferenceHelp.read(SPKey.KEY_MAP_MODE);
    setState(() {
      buildId = value;
      account = accountValue;
      if(mapMode == "1"){
        mapType = "卫星图";
        confirmedMapType = "卫星图";
      }else{
        mapType = "2D平面图";
        confirmedMapType = "2D平面图";
      }
      print('$mapMode读取的mapType$confirmedMapType');
      isBuildIdObtained = true;
//      if(StringUtil.isNotEmpty(ObjMapPath.pathUrl)){
        _hiSocket = HiSocket({});
        _hiSocket.open('$buildId').listen((value) {
//        print("来自websocket的:");
//        print(value);
          handleMessage(value);
        });
        _getAllInfo();
        _getIconDictionary();
        _getPersonTypeList();
        _getRiskZone();
//      }else{
//        eMsg = "未找到jpg地图文件夹";
//      }

    });
  }

  _runTimer() {
    if (infoDictionary == null) {
      return;
    }
    if (iconDictionary == null) {
      return;
    }
    if (lock) {
      return;
    } else {
      lock = true;
    }
    _startTimer = Timer.periodic(Duration(milliseconds: 1000 * 1), (timer) {
      LocationReq req = LocationReq(requestMethod: "summary", value: account);
      print(req.toString());
      _hiSocket.send(req.toString());
    });
    _alarmInfoTimer = Timer.periodic(Duration(milliseconds: 5000), (timer) {
      _getAlarmSn();
    });
  }

  _getAlarmSn() async {
    if (isResumed) {
      await DioHttpClient.requestGet(
          context,
          MapHttpUrl.GET_ALARM_SN_URL,
          {},
          new NetListenerImpl((Response response) {
            if (response != null && response.data != null) {
              ResMapAlarmInfo info = ResMapAlarmInfo.fromJson(response.data);
              setState(() {
                alarmSns = info.data;
              });
//            print("info");
//            print(info);
            }
          }, (CommonRes errorRes) {}));
    }
  }

  getSummaryInstanceOnlyOnce() {
    LocationReq req = LocationReq(requestMethod: "summary", value: account);
    print(req.toString());
    _hiSocket.send(req.toString());
  }

  formSend() {
    _summaryTimer =
        Timer.periodic(Duration(milliseconds: 1000 * summaryInterval), (timer) {
      LocationReq req = LocationReq(requestMethod: "summary", value: account);
      print(req.toString());
      _hiSocket.send(req.toString());
    });
    _locationTimer = Timer.periodic(
        Duration(milliseconds: 1000 * locationInterval), (timer) {
      LocationReq req = LocationReq(requestMethod: "location", value: account);
      _hiSocket.send(req.toString());
    });
  }

  confirmFilter() {
    setState(() {
      print(mapShowStatusList);
      confirmedMapShowStatusList[0] = mapShowStatusList[0];
      confirmedMapShowStatusList[1] = mapShowStatusList[1];
      confirmedMapShowStatusList[2] = mapShowStatusList[2];
//      confirmedMapShowStatusList[3] = mapShowStatusList[3];

      confirmedMapType = (mapType == "2D平面图") ? "2D平面图" : "卫星图";

      confirmedChosenJobIds = [];
      if (chosenJobIds != null && chosenJobIds.length > 0) {
        chosenJobIds.forEach((element) {
          confirmedChosenJobIds.add(element);
        });
      }

      if (chosenDeptTreeInfo != null) {
        confirmedChosenDeptTreeInfo = DeptTreeInfo(
            id: chosenDeptTreeInfo.id, label: chosenDeptTreeInfo.label);
      } else {
        confirmedChosenDeptTreeInfo = null;
      }
    });

    controller
        ?.evaluateJavascript(
            'setDomTitleShowFlag(${confirmedMapShowStatusList[0]})')
        ?.then((result) {});

//    if(confirmedMapShowStatusList[1]){
//      controller
//          ?.evaluateJavascript(
//          'addRiskZone($bundlePoints)')
//          ?.then((result) {});
//    }else{
//      controller
//          ?.evaluateJavascript(
//          'toggoleRiskZone(false)')
//          ?.then((result) {});
//    }

    logFilterInfo();
    Navigator.of(context).pop();
  }

  logFilterInfo() {
    print("打印确认的信息");
    print(confirmedMapShowStatusList);
    print(confirmedMapType);
    print(confirmedChosenJobIds);
    print(confirmedChosenDeptTreeInfo?.label);
    print("打印确认的信息结束");

    _setShowStatusList();
    _setChosenMapType();
    _setChosenDeptId(confirmedChosenDeptTreeInfo?.id ?? -1);
    _setChosenJobIds();
    _doFilter();
  }

  bool hasValidSn() {
    return chosenSn != null;
  }

  getSearchTextColor() {
    if (hasValidSn()) {
      return Colors.black;
    }
    return Color.fromRGBO(0, 0, 0, 0.5);
  }

  getFullInfo() {
    if (chosenSn != null) {
      showBottomSheet2(true, false, chosenSn);
    }
  }

  jumpToDetail(typeName, id, name) {
    if (typeName == "内部员工") {
      NavigatorUtil.push(context, PageEmployeeDetail(id, name));
    } else if (typeName == "承包商") {
      NavigatorUtil.push(context, PageWorkerDetail(id));
    } else if (typeName == "外来访客") {
      NavigatorUtil.push(context, PageGuestDetail(id));
    } else if (typeName == "外来车辆") {
      NavigatorUtil.push(context, PageOuterCarDetail(id, name));
    } else if (typeName == "内部车辆") {
      NavigatorUtil.push(context, PageInnerCarDetail(id, name));
    }
  }

  get _searchBar => Offstage(
        offstage: _isTrackingMode(),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(cornerRadius),
          ),
          margin: EdgeInsets.fromLTRB(10, 3, 10, 0),
          padding: EdgeInsets.only(left: 12),
          child: Row(
            children: [
              Icon(Icons.search, color: Color.fromRGBO(0, 0, 0, 0.5)),
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      margin: hasValidSn()
                          ? EdgeInsets.only(left: 6)
                          : EdgeInsets.all(12),
                      child: Text(
                          chosenSn != null &&
                                  StringUtil.isNotEmpty(chosenSn.name)
                              ? chosenSn.name
                              : hintText,
                          style: TextStyle(color: getSearchTextColor())),
                    ),
                    Offstage(
                      offstage: !hasValidSn(),
                      child: IconButton(
                        onPressed: () {
                          setState(() {
                            chosenSn = null;
                          });
                        },
                        icon: Icon(Icons.clear,
                            color: Color.fromRGBO(0, 0, 0, 0.5)),
                      ),
                    )
                  ],
                ),
                flex: 1,
              )
            ],
          ),
        ),
      );

  _isTrackingMode(){
    return realTimeTrackTarget != null;
  }

  _getRiskZone() async {
    await DioHttpClient.requestGet(
        context,
        MapHttpUrl.GET_RISK_ZONE_URL,
        {},
        new NetListenerImpl((Response response) {
          if (response != null && response.data != null) {
            ResRiskZone res = ResRiskZone.fromJson(response.data);
            if (res != null && res.code == 0) {
              RiskZoneData data = res.data;
              if (data != null) {
                List<RiskZoneInfo> infoList = data.data;
                if (infoList != null && infoList.length > 0) {
                  print('infoLIst-${infoList.length}');
                  infoList.forEach((info) {
                    if (info != null) {
                      RiskZoneRail rail = info.podRiskRail;
                      if(rail != null){
                        String floorNo = rail.floorNo;
                        int floorId = int.parse(floorNo.substring(5));
                        List<RiskZonePoint> points = info.points;
                        if(points != null && points.length > 0){
                          points.forEach((element) {
                            element.floorId = floorId;
                          });
                        }
                        RiskZoneBundleItem item = RiskZoneBundleItem();
                        item.floorId = floorId;
                        item.level = rail.level;
                        item.points = points;
                        bundleItems.add(item);
                      }
                    }
                  });
                  bundlePoints = convert.jsonEncode(bundleItems);
                  print('合并后的$bundlePoints');
                }
              }
            }
          }
        }, (CommonRes errorRes) {}));
  }
}
